<template>
  <h2>User Information</h2>
  <el-form :rules="rules" ref="ruleFormRef" :label-position="labelPosition" label-width="auto" :model="information"
    style="max-width: 600px">
    <el-form-item label="User ID" :label-position="itemLabelPosition" prop="userId" required>
      <el-input v-model="information.userId" size="large" />
    </el-form-item>
    <el-form-item label="Password" :label-position="itemLabelPosition" prop="password" required>
      <el-input v-model="information.password" size="large" type="password" />
    </el-form-item>
    <el-form-item label="Repeat Password" :label-position="itemLabelPosition" prop="rePassword" required>
      <el-input v-model="information.rePassword" size="large" type="password" />
    </el-form-item>
    <el-form-item label="Verity" :label-position="itemLabelPosition" prop="checkcode" required>
      <div class="verify-code-container">
        <el-input v-model="information.checkcode" size="large" style="width: 200px" />
        <canvas ref="verifyCanvas" @click="refreshVerifyCode" class="verify-code-canvas"></canvas>
      </div>
    </el-form-item>
  </el-form>
  <h2>Account Information</h2>
  <el-form :label-position="labelPosition" label-width="auto" :model="information" style="max-width: 600px">
    <el-form-item label="First Name" :label-position="itemLabelPosition">
      <el-input v-model="information.firstName" size="large" />
    </el-form-item>
    <el-form-item label="LastName" :label-position="itemLabelPosition">
      <el-input v-model="information.lastName" size="large" />
    </el-form-item>
    <el-form-item label="Email" :label-position="itemLabelPosition">
      <el-input v-model="information.email" size="large" />
    </el-form-item>
    <el-form-item label="Phone" :label-position="itemLabelPosition">
      <el-input v-model="information.phone" size="large" />
    </el-form-item>
    <el-form-item label="Address 1" :label-position="itemLabelPosition">
      <el-input v-model="information.address1" size="large" />
    </el-form-item>
    <el-form-item label="Address 2" :label-position="itemLabelPosition">
      <el-input v-model="information.address2" size="large" />
    </el-form-item>
    <el-form-item label="City" :label-position="itemLabelPosition">
      <el-input v-model="information.city" size="large" />
    </el-form-item>
    <el-form-item label="State" :label-position="itemLabelPosition">
      <el-input v-model="information.state" size="large" />
    </el-form-item>
    <el-form-item label="Zip" :label-position="itemLabelPosition">
      <el-input v-model="information.zip" size="large" />
    </el-form-item>
    <el-form-item label="Country" :label-position="itemLabelPosition">
      <el-input v-model="information.country" size="large" />
    </el-form-item>
  </el-form>
  <h2>Profile Information</h2>
  <el-form :label-position="labelPosition" label-width="auto" :model="information" style="max-width: 600px">
    <el-form-item label="Language Preference" :label-position="itemLabelPosition">
      <el-select v-model="information.languagePreference" placeholder="Select language" size="large"
        style="width: 300px">
        <el-option label="English" value="english" />
        <el-option label="Japanese" value="japanese" />
        <el-option label="Chinese" value="chinese" />
      </el-select>
    </el-form-item>
    <el-form-item label="Favourite Category" :label-position="itemLabelPosition">
      <el-select v-model="information.favouriteCategory" placeholder="Select category" size="large"
        style="width: 300px">
        <el-option label="FISH" value="FISH" />
        <el-option label="DOGS" value="DOGS" />
        <el-option label="REPTILES" value="REPTILES" />
        <el-option label="CATS" value="CATS" />
        <el-option label="BIRDS" value="BIRDS" />
      </el-select>
    </el-form-item>
    <el-form-item label="Enable MyList" :label-position="itemLabelPosition">
      <el-checkbox v-model="information.listOption" size="large" style="transform: scale(1.5)" />
    </el-form-item>
    <el-form-item label="Enable MyBanner" :label-position="itemLabelPosition">
      <el-checkbox v-model="information.bannerOption" size="large" style="transform: scale(1.5)" />
    </el-form-item>
  </el-form>
  <el-button type="primary" size="large" @click="() => handleRegister(ruleFormRef)">Save Account</el-button>
</template>

<script lang="ts" setup>

// 导入所需的 Vue 组件和路由
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, FormRules, FormInstance } from 'element-plus'
// 导入自定义的网络请求模块
import apiClient from '@/api/api'
// 初始化路由实例
const router = useRouter()
// 设置表单标签的位置
const labelPosition = ref('left')
const itemLabelPosition = ref('left')
interface formRules {
  userId: string
  password: string
  rePassword: string
  checkcode: string
}
// 创建响应式表单数据对象
const information = reactive({
  userId: '', // 用户id
  password: '', // 密码
  rePassword: '', // 确认密码
  checkcode: '', // 验证码
  firstName: '', // 名
  lastName: '', // 姓
  email: '', // 邮箱
  phone: '', // 电话
  address1: '', // 地址1
  address2: '', // 地址2
  city: '', // 城市
  state: '', // 州
  zip: '', // 邮编
  country: '', // 国家
  languagePreference: 'english', // 语言偏好，默认英语
  favouriteCategory: 'FISH', // 喜爱的类别，默认FISH
  listOption: false, // 是否启用MyList
  bannerOption: false // 是否启用MyBanner
})
const verifyCanvas = ref<HTMLCanvasElement | null>(null)
const verifyCode = ref('')

// 生成随机验证码
const generateVerifyCode = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let code = ''
  for (let i = 0; i < 4; i++) {
    code += chars[Math.floor(Math.random() * chars.length)]
  }
  verifyCode.value = code
  return code
}

// 绘制验证码
const drawVerifyCode = () => {
  const canvas = verifyCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 设置画布大小
  canvas.width = 100
  canvas.height = 40

  // 填充背景
  ctx.fillStyle = '#f0f0f0'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 生成新验证码
  const code = generateVerifyCode()

  // 绘制文字
  ctx.font = 'bold 24px Arial'
  ctx.textBaseline = 'middle'
  for (let i = 0; i < code.length; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`
    ctx.fillText(code[i], 20 + i * 20, canvas.height / 2)
  }

  // 绘制干扰线
  for (let i = 0; i < 4; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
}

// 刷新验证码
const refreshVerifyCode = () => {
  drawVerifyCode()
}

// 组件挂载时初始化验证码
onMounted(() => {
  drawVerifyCode()
})
// 表单实例引用
const ruleFormRef = ref<FormInstance>()

// 表单验证规则
const rules = reactive<FormRules<formRules>>({
  // 用户ID验证规则
  userId: [
    { required: true, message: 'Please input user ID', trigger: 'blur' },
    { min: 3, max: 20, message: 'Length should be 3 to 20 characters', trigger: 'blur' }
  ],
  // 密码验证规则
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' },
    { min: 6, message: 'Password must be at least 6 characters', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/, message: 'Password must contain at least one uppercase letter, one lowercase letter and one number', trigger: 'blur' }
  ],
  // 确认密码验证规则
  rePassword: [
    { required: true, message: 'Please confirm your password', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value === '') {
          callback(new Error('Please input the password again'))
        } else if (value !== information.password) {
          callback(new Error('Two inputs don\'t match!'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
  // 验证码验证规则
  checkcode: [
    { required: true, message: 'Please input verification code', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value === '') {
          callback(new Error('Please input the verification code'))
        } else if (value.toLowerCase() !== verifyCode.value.toLowerCase()) {
          callback(new Error('Verification code is incorrect'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
})
// 注册数据接口定义
interface RegisterData {
  sign: {
    username: string
    password: string
  }
  account: {
    username: string
    email: string
    firstname: string
    lastname: string
    status: string
    address1: string
    address2: string
    city: string
    state: string
    zip: string
    country: string
    phone: string
  }
  profile: {
    username: string
    favoriteCategory: string
    bannerOption: boolean
    myListOption: boolean
    languagePreference: string
  }
}
// 注册按钮点击事件
const handleRegister = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    console.log(valid)
    if (!valid) {
      ElMessage.warning('Please fill in all required fields correctly')
      return
    }
    // 继续处理注册逻辑
    if (information.password !== information.rePassword) {
      ElMessage.error('Passwords do not match')
      return
    }
    if (information.checkcode.toLowerCase() !== verifyCode.value.toLowerCase()) {
      ElMessage.error('Verification code is incorrect')
      return
    }
    try {
      // 查看用户名是否重复
      apiClient.get(`/users/${information.userId}`)
      .then(response => {
        if (response.data.message === "Exist") {
          ElMessage.warning('Username already exists')
          return
        }
      })
      // 发送注册请求
      const registerData: RegisterData = {
        sign: {
          username: information.userId,
          password: information.password
        },
        account: {
          username: information.userId,
          email: information.email,
          firstname: information.firstName,
          lastname: information.lastName,
          status: 'ok',
          address1: information.address1,
          address2: information.address2,
          city: information.city,
          state: information.state,
          zip: information.zip,
          country: information.country,
          phone: information.phone
        },
        profile: {
          username: information.userId,
          favoriteCategory: information.favouriteCategory,
          bannerOption: information.bannerOption,
          myListOption: information.listOption,
          languagePreference: information.languagePreference
        }
      }
      apiClient.post('/users', registerData)
        .then(response => {
          console.log(response)
          if (response.data.status === 0) {
            ElMessage.success('Registration successful')
            router.push('/login')
          } else {
            ElMessage.error(response.data.message)
          }
        })
        .catch(error => {
          console.log(error)
          ElMessage.error('Registration failed')
        })
    } catch (error) {
      console.log(error)
      ElMessage.error('Registration failed')
    } finally {
      refreshVerifyCode()
    }
  })
}
</script>

<style scoped>
.el-form {
  margin-top: 0%;
}

.el-form .el-form-item {
  margin-bottom: 30px;
}

.el-input {
  width: 300px;
}

.el-input__inner {
  height: 45px !important;
  font-size: 16px !important;
  padding: 0 15px !important;
}

.el-button {
  margin-bottom: 5%;
  width: 300px;
  height: 45px;
  font-size: 16px;
}

.verify-code-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.verify-code-canvas {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>